package com.yiwei.ydd.activity;

import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiwei.ydd.R;
import com.yiwei.ydd.adapter.AccountMonthAdapter;
import com.yiwei.ydd.adapter.ExpandPacketAdapter;
import com.yiwei.ydd.adapter.RetrunCashGroupAdapter;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.PageBean;
import com.yiwei.ydd.api.model.CashBackIndexModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.Spans;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.CustomExpandableListView;
import com.yiwei.ydd.view.V19FrameLayout;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class ReturnCashActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.expand_list)
    RecyclerView expandList;
    @BindView(R.id.txt_this_month)
    TextView txtThisMonth;
    @BindView(R.id.txt_is_back)
    TextView txtIsBack;
    @BindView(R.id.txt_last_back)
    TextView txtLastBack;
    @BindView(R.id.txt_total)
    TextView txtTotal;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.layout_has_data)
    LinearLayout layoutHasData;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    private int currentPage = 1;
    private Unbinder unbiner;
    private AccountMonthAdapter accountMonthAdapter;
    private RetrunCashGroupAdapter expandPacketAdapter;
    private boolean isOkRefresh = false;
    private boolean isNoData = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_cash_record);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("返现记录");
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
                    //底部加载
                    if (isOkRefresh&&!isNoData) {
                        isOkRefresh = false;
                        currentPage++;
                        getCashBackLists(currentPage);

                    }
                }
                if (refresh != null) {
                    refresh.setEnabled(scrollView.getScrollY() == 0);
                }
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getCashBackLists(1);
                getCashBackIndex();
            }
        });

        accountMonthAdapter = new AccountMonthAdapter(this);
        list.setAdapter(accountMonthAdapter);


        expandPacketAdapter = new RetrunCashGroupAdapter(this);
//        expandList.setGroupIndicator(null);
//        expandList.setDivider(null);
        expandList.setAdapter(expandPacketAdapter);
//        expandList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
//            @Override
//            public void onGroupExpand(int groupPosition) {
//                for (int i = 0; i < expandPacketAdapter.getGroupCount(); i++) {
//                    // ensure only one expanded Group exists at every
//                    if (groupPosition != i){
//                        expandList.collapseGroup(i);
//                    }
//                }
//            }
//        });


        getCashBackIndex();
        getCashBackLists(1);
    }

    public void getCashBackLists(int page) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        PageBean bean = new PageBean();
        bean.page = page;
        Api.api_service.getCashBackLists(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                        isOkRefresh = true;
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.datas == null || result.datas.size() == 0) {
                        isNoData = true;
                    } else {
                        isNoData = false;
                    }
                    expandPacketAdapter.add(result.datas, page == 1);
                    if (expandPacketAdapter.getItemCount() == 0 && accountMonthAdapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                        layoutHasData.setVisibility(View.GONE);
//                        for (int i = 0; i < expandPacketAdapter.getGroupCount(); i++) {
//                            // ensure only one expanded Group exists at every
//                                expandList.expandGroup(i);
//                        }
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                        layoutHasData.setVisibility(View.VISIBLE);
                    }
                });
    }

    public void getCashBackIndex() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }


        refresh.setRefreshing(true);
        Api.api_service.getCashBackIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setIndexData(result.datas);
                });
    }

    private void setIndexData(CashBackIndexModel.DatasBean datas) {
        CashBackIndexModel.DatasBean.TotalBean total = datas.total;

        txtThisMonth.setText(total.this_month);
        txtIsBack.setText(getTextInfo("累计返还总额", total.is_back));
        txtLastBack.setText(getTextInfo("剩余返还总额", total.last_back));
        txtTotal.setText(getTextInfo("充值累计金额", total.total));
        accountMonthAdapter.update(datas.item);
    }

    private Spanned getTextInfo(String one, String two) {
        if (TextUtils.isEmpty(two)) {
            two = "";
        }
        return Spans.with(this).font(one + "\n", getResources().getDimensionPixelSize(R.dimen.x22), 0x8cFEFEFE).
                font(two, getResources().getDimensionPixelSize(R.dimen.x36), 0xffFEFEFE).
                build();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.btn_submit, R.id.txt_right, R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                Util.startActivity(this, PacketRechargeActivity.class);
                break;
            case R.id.txt_right:
                Util.startActivity(this, RechargeRecordActivity.class);
                break;
        }

    }
}
